<template>
  <div class="control-panel">
    <!-- 顶部选择区域 -->
    <div class="panel-section top-section">
      <div class="select-container">
        <el-row :gutter="20">
          <el-col :span="10">
            <!-- 卡密文档选择下拉框 -->
            <el-select
                v-model="selectedValue"
                placeholder="请选择一个卡密文档"
                class="select-box"
                @change="handleSelectChange"
            >
              <el-option
                  v-for="item in selectedFiles"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="!item.exist"
              >
                <template #default>
                  <div class="custom-option">
                    <span class="option-label">{{ item.label }}</span>
                    <el-icon class="delete-icon" @click.stop="deleteItem(item.value)">
                      <Delete/>
                    </el-icon>
                  </div>
                </template>
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="10">
            <el-button @click="handleSelectFile" class="btn">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-button>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <!-- 服务商选择下拉框 -->
            <el-select
                v-model="selectedProvider"
                placeholder="请选择服务商"
                filterable
                class="select-box"
            >
              <el-option
                  v-for="item in providerList"
                  :key="item.id"
                  :label="`${item['real_name']} (${item.phone})`"
                  :value="item.id"
              />
            </el-select>
          </el-col>
          <el-col :span="6">
            <!-- 状态选择 -->
            <el-radio-group
                v-model="status"
                @change="handleStatusChange"
            >
              <el-radio-button label="启用" value="1"/>
              <el-radio-button label="禁用" value="0"/>
            </el-radio-group>
          </el-col>
          <el-col :span="5">
            <el-button type="primary">确认绑定</el-button>
          </el-col>
        </el-row>
      </div>
      <el-divider content-position="left">范围绑定</el-divider>
      <div class="select-container">
        <el-row :gutter="20">
          <el-col :span="10">
            <div class="flex gap-4">
              <span></span>
              <el-input
                  placeholder="请输入起始卡号"
                  v-model="startCardNumber"
              />
              -
              <el-input
                  placeholder="请输入结束卡号"
                  v-model="endCardNumber"
              />
            </div>
          </el-col>
          <el-col :span="8">
            <el-button type="primary">确认绑定</el-button>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 卡片列表 -->
    <div class="panel-section card-list">
      <span style="margin-bottom: 15px;">卡片列表</span>
      <el-table
          ref="treeTable"
          :data="treeData"
          style="width: 100%"
          height="300"
          :row-key="row => row.id"
          border
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
      </el-table>
    </div>

    <!-- 底部操作区域 -->
    <!--    <div class="panel-footer">-->
    <!--    </div>-->
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue';
import {SelectFile} from "../../wailsjs/go/local/FileService.js";
import {
  AddCardFileInfo,
  DeleteCardFileInfo,
  GetCardInfoList,
  LoadCardFile
} from "../../wailsjs/go/local/CardFileService.js";
import {GetAgentSelectList} from "../../wailsjs/go/remote/AgentService.js";

const status = ref("1"); // Default to 'enabled'
const selectedValue = ref('')
const selectedFiles = ref([])
const providerList = ref([]);
const selectedProvider = ref('');

const startCardNumber = ref(0)
const endCardNumber = ref(0)

const deleteItem = async (value) => {
  const success = DeleteCardFileInfo(value)
  if (!success) {
    console.log("文件添加失败")
    return
  }
  selectedFiles.value = selectedFiles.value.filter(option => option.value !== value)
}

// Function to handle file selection with Wails
const handleSelectFile = async () => {
  const path = await SelectFile()
  if (path === "") {
    return
  }
  const success = AddCardFileInfo(path)
  if (!success) {
    console.log("文件添加失败")
    return
  }
  await getCardFileInfoList()
}

const handleSelectChange = async (value) => {
  await getBoxInfoList(value)
}


const treeData = ref([]);

const selectedItems = ref([]);

const handleSelectionChange = (selection) => {
  selectedItems.value = selection;
};

// 获取表格引用
const treeTable = ref();

const selectItem = () => {
  // 找到子节点2-1的数据项
  const itemToSelect = findItemInTree(treeData.value, 5);
  console.log('e', itemToSelect);
  // 使用toggleRowSelection方法选中或取消选中
  treeTable.value.toggleRowSelection(itemToSelect, true);
};

// Function to handle status change
const handleStatusChange = (newStatus) => {
  console.log('Status changed to:', newStatus);
  // Add your logic here based on the new status
};


// 递归查找children中有没有符合的目标
const findItemInTree = (tree, itemId) => {
  for (const item of tree) {
    if (item.id === itemId) {
      return item;
    }
    if (item.children) {
      const found = findItemInTree(item.children, itemId);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// Define an asynchronous function to fetch card file info list
const getCardFileInfoList = async () => {
  selectedFiles.value = []
  try {
    // Call the Go function asynchronously and wait for the result
    const cardList = await GetCardInfoList();

    // Ensure cardList is an array before proceeding
    if (Array.isArray(cardList)) {
      // Iterate over the cardList array and print each card's information
      cardList.forEach((card) => {
        console.log(card)
        const newFile = {
          value: card["id"], // Assuming `id` is used as the value
          label: card["file_name"], // Use `file_name` as the label
          exist: card["exist"], // Use `file_name` as the label
        };
        // Update `selectedFiles` with the new file object
        selectedFiles.value.push(newFile);
      });
    } else {
      console.error("cardList is not an array:", cardList);
    }
    // You can add additional logic here to handle or process the cardList as needed
  } catch (error) {
    // Log any errors that occur during the fetch process
    console.error("Error fetching card list:", error);
  }
};

//
const getBoxInfoList = async (value) => {
  // console.log("getBoxInfoList", value)
  // LoadCardFile
  treeData.value = await LoadCardFile(value);
}

const loadAgentSelect = async () => {
  const agentList = await GetAgentSelectList()
  if (agentList && Array.isArray(agentList.list)) {
    providerList.value = agentList.list;
    // console.log("providerList", providerList.value)
  } else {
    console.error("GetAgentSelectList 返回的格式不正确");
  }

}

// 使用 onMounted 生命周期钩子
onMounted(() => {
  console.log('组件已挂载');
  // 在这里执行你想在页面加载完成时运行的代码
  getCardFileInfoList()
  loadAgentSelect()
});
</script>

<style scoped>
.control-panel {
  display: flex;
  flex-direction: column;
  padding-bottom: 50px; /* 给固定的footer留出空间 */
  overflow-y: auto; /* 内容过多时滚动 */
}

.panel-section {
  width: 100%;
  margin-bottom: 10px; /* 间距调整 */
  box-sizing: border-box;
}

.top-section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
}

.select-container {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.select-box {
  width: 100%;
}

.custom-option {
  display: flex;
  align-items: center;
}

.option-label {
  flex: 1;
}

.delete-icon {
  cursor: pointer;
  color: red;
}

.panel-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px 20px;
  display: flex;
  justify-content: center; /* 水平居中对齐 */
}

.confirm-button {
  /* background-color: #409eff;
  color: #fff;
  border: none;
  padding: 8px 16px;
  cursor: pointer;

   */
}
</style>



